package org.example.demo1.servlets.LoginPage;

import com.google.gson.Gson;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.demo1.Entity.User;
import org.example.demo1.utils.ChineseIdentifierUtils;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import static org.example.demo1.utils.ChineseIdentifierUtils.identify;
import static org.example.demo1.utils.InquireTools.getUserInformationByEmail;
import static org.example.demo1.utils.InquireTools.getUserInformationByPhone;
@WebServlet("/API/verify")
public class UserContactInfoQueryService extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String EmailOrPhone = req.getParameter("EmailOrPhone");
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        ChineseIdentifierUtils.IdentifierType type = identify(EmailOrPhone);
        Map<String, Object> data = new HashMap<>();
        User u=null;
        if (type == ChineseIdentifierUtils.IdentifierType.EMAIL) {
            u=getUserInformationByEmail(EmailOrPhone);
        }else if(type == ChineseIdentifierUtils.IdentifierType.PHONE){
            u=getUserInformationByPhone(EmailOrPhone);
        }else{
            u=null;
        }
        if(u!=null){
            data.put("status", "success");
            data.put("code", 201);
            data.put("message", "该邮箱或电话号已被使用");
        }else{
            data.put("status", "success");
            data.put("code", 200);
            data.put("message", "该邮箱或电话号未被使用");
        }
        // 使用Gson或Jackson将对象转为JSON
        String json = new Gson().toJson(data);

        // 发送响应
        PrintWriter out = resp.getWriter();
        out.print(json);
        out.flush();
    }
}
